import $ from 'jquery'

window.$util = {
    // 字符串转dom对象
    createXml(str) {
        if (document.all) {
            var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
            xmlDom.loadXML(str);
            return xmlDom;
        } else
            return new DOMParser().parseFromString(str, "text/xml");
    },

    // dom对象转字符串
    htmlToString(document) {
        let retVal = '';
        if (document.doctype) {
            retVal = new XMLSerializer().serializeToString(document.doctype);
        }
        if (document.documentElement) {
            retVal += document.documentElement.outerHTML;
        }
        return retVal;
    },

    getBase64(imgUrl) {
        return new Promise((resolve, reject) => {
            window.URL = window.URL || window.webkitURL;
            var xhr = new XMLHttpRequest();
            xhr.open("get", imgUrl, true);
            // try by geeker CORS error
            xhr.header('Access-Control-Allow-Origin', "*");
            xhr.header('Access-Control-Allow-Methods', 'GET');
            xhr.header("Access-Control-Allow-Headers", "accept, content-type");
            xhr.header("Access-Control-Max-Age", "1728000");
            // 至关重要
            xhr.responseType = "blob";
            xhr.onload = function () {
                if (this.status == 200) {
                    //得到一个blob对象
                    var blob = this.response;
                    console.log()
                    console.log("blob", blob)
                    //  至关重要
                    let oFileReader = new FileReader();
                    oFileReader.onloadend = function (e) {
                        let base64 = e.target.result;
                        console.log("方式一》》》》》》》》》", base64)
                        if (base64.search('/svg+') > -1) {
                            reject({'error': "无图片"});
                        } else {
                            resolve({image: base64});
                        }

                    };
                    oFileReader.readAsDataURL(blob);
                } else {
                    reject({'error': "无图片"});
                }
            }
            xhr.send();
        });
    },


    // error report
    errorReport (msg) {
        console.log(msg)
        chrome.runtime.sendMessage({ type: 'error-report', url: window.location.href, msg: msg })
    },

    getQualification (str) {
        if (!str) return ''
        var match = str.match(/初中|高中|小学|本科|大专|中专|研究生?|硕士|博士生?/)
        return match ? match[0] : str
    },
    getWorkStateStr (str) {
        // 当前意向(1:暂不考虑, 2:等待机会,3:正在跟进,4:确认合作,5:黑名单)
        var status = [
            {
                str: '离职',
                reg: /离职|dimission/
            },
            {
                str: '看看新',
                reg: /看看新|新环境|工作机会|newjob|在职找工作/
            },
            {
                str: 2,
                reg: /急寻|正在找工作/
            },
            {
                str: 1,
                reg: /暂不找工作/
            },
            {
                str: '跳槽',
                reg: /跳槽|job-hopping/
            },
            {
                str: '在职',
                reg: /在职|Onjob/
            }
        ]
        for (var i = 0; i < status.length; i++) {
            var item = status[i]
            if (item.reg.test(str)) {
                return item.str
            }
        }
        return ''
    },
    getSalaryMax (str) {
        var temp = str.match(/\d+/g)
        if (temp) {
            return temp[temp.length - 1]
        }
        return 0
    },
    getSalaryMin (str) {
        var temp = str.match(/\d+/g)
        return temp ? temp[0] : 0
    },
    toDataURL(src, callback){
        var xhr = new XMLHttpRequest();
        xhr.open('get', src);
        xhr.responseType = 'blob';
        xhr.onload = function(){
            // console.log(xhr.response)
            // callback && callback(xhr.response)
            var fr = new FileReader()
            fr.onload = function(){
                callback && callback(this.result)
            };
            fr.readAsDataURL(xhr.response); // async call
        };
        xhr.send();
    },

    // 只获取当前节点的文本内容, 不含子节点的text
    getChildText (el) {
        var obj = $(el).clone()
        obj.find(':nth-child(n)').remove()
        var html = obj.text() || ''
        html = html.replace(/<!---->/g, '')
        return html
    },

    getStartToEndTime (time) {
        //console.log("--->开始处理时间："+time.replace(/\s/g, ''))
        if (!time) return {}
        var splitChar = $util.getSplitChar(time);
        var workTime = time.replace(/\s/g, '').split(splitChar)
        //console.log("--->格式化时间："+workTime.length)
        var start = workTime[0] || ''
        start = start.replace(/[年月\.]/g, '-')
        if (start) {
            start = new Date(start).getTime()
        }
        var end = workTime[1] || ''
        end = end.replace(/[年月\.]/g, '-')
        //console.log("--->"+end)
        if (end.indexOf('present') !== -1 || end.indexOf('至今') !== -1) {
            // 工作至今的时间
            end = 1960992000000
        } else if (end) {
            end = new Date(end).getTime()
        } else {
            start
        }
        //console.log("--->时间处理完成："+time)
        return {start: start || undefined, end: end || undefined}
    },
    getSplitChar(str){
        if(str.indexOf("-")!=-1){
            return "-";
        }else if(str.indexOf("—")!=-1){
            return "—";
        }else if(str.indexOf("～")!=-1){
            return "～";
        }else if(str.indexOf("–")!=-1){
            return "–";
        }
        return "not found";
    },
    formatStr (str) {
        if (str) {
            return str.replace(/<br>/g, '\n').trim().replace(/&nbsp;|&middot;|&ldquo;|&rdquo;|&madash;/gi, ' ')
        }
        return ''
    },

    formatStrLine (str) {
        if (str) {
            str = str.split('<br>')
            str = str.map(function (str) {
                return $('<div>' + str.trim() + '</div>').text()
            })
            return $util.formatStr(str.join('\n'))
        }
        return ''
    },
    getEducationalAttainment (str) {
        let q = str.replace(/\s/g, '')
        switch (q) {
            case 'JuniorCollege':
                return '大专'
            case 'Postdoctor':
                return '博士后'
            case 'Doctorate':
                return '博士'
            case 'MBA':
                return 'EMBA'
            case 'Master':
                return '硕士'
            case 'Bachelor':
                return '本科'
            case 'SpecialSchool':
                return '中专'
            case 'TechnicalSchool':
                return '中技'
            case 'SeniorHighSchool':
                return '高中'
            case 'JuniorHighSchool':
                return '初中'
        }
        return str
    },
    getEducation (str) {
        let q = str.replace(/\s/g, '').match(/小学|初中|高中|中专|大专|本科|硕士|博士/)
        if(!q) return
        switch (q[0]) {
            case '小学':
                return '1'
            case '初中':
                return '2'
            case '高中':
                return '3'
            case '中专':
                return '4'
            case '大专':
                return '5'
            case '本科':
                return '6'
            case '硕士':
                return '7'
            case '博士':
                return '8'
        }
        return str
    }
}



export function urlToBase64(url) {
    return new Promise((resolve) => {
      let canvas = document.createElement('canvas')
      let ctx = canvas.getContext('2d')
      let img = new Image()
      img.crossOrigin = 'Anonymous';
      img.onload = function () {
        canvas.height = img.height;
        canvas.width = img.width;
        ctx?.drawImage(img, 0, 0);
        // 获取Base64
        var dataURL = canvas.toDataURL('image/png');
        // console.log('base64地址：', dataURL)
        resolve(dataURL)
      };
      img.src = url;
    })
  }

export function base64ToBlob(dataURL) {
    var arr = dataURL.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}

export function dataURLtoFile(dataurl, filename) {
    let arr = dataurl.split(","),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    filename = filename + '.' + mime.split('/')[1]
    return new File([u8arr], filename, { type: mime });
  }

